import { highlight, languages } from 'prismjs'
import 'prismjs/components/prism-json'
import { isJSON } from 'src/utils/utils'
import { computed, h, inject } from 'vue'

const formatJson = (json = '', indent = 4) => {
  const parseJson = JSON.parse(json)
  if (Array.isArray(parseJson) && parseJson.length === 1) return JSON.stringify(parseJson[0], null, indent)
  return JSON.stringify(parseJson, null, indent)
}
export default {
  name: 'QCodePrism',
  props: { code: String, lang: { type: String, default: 'json' }, dark: Boolean, classes: String },
  setup (props) {
    const isDark = inject('isDark')
    const nonJSON = computed(() => !props.code || !isJSON(props.code))
    const formatCode = computed(() => nonJSON.value ? props.code || '' : formatJson(props.code))
    const themes = computed(() => isDark.value || props.dark ? 'doc-code-dark' : 'doc-code')
    const className = computed(
      () => `language-${props.lang} ${props.classes || ''} ${nonJSON.value ? 'non-json' : ''} ${themes.value}`)
    return () => h('pre', { class: className.value }, [
      h('code', {
        innerHTML: highlight(formatCode.value, languages[props.lang], props.lang)
      })
    ])
  }
}